using System.Net;
using System.Web;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Util;

namespace Geekeradmin.Filters
{
  /// <summary>
  /// 日志记录
  /// </summary>
  public class CustomLogAction : Attribute, IActionFilter
  {
    private readonly ILogger<CustomLogAction> logger;

    private readonly IMySqlSugarService mySqlSugar;

    public CustomLogAction(ILogger<CustomLogAction> logger, IMySqlSugarService mySqlSugar)
    {
      this.logger = logger;
      this.mySqlSugar = mySqlSugar;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
      var paramsdata = String.Join(
        '&',
        context.HttpContext.Request.Query.Select(o =>
        {
          return string.Format("{0}={1}", o.Key, o.Value);
        })
      );
      //var paramsdatab = context.HttpContext.Request.QueryString.Value;
      var controller = context.HttpContext.GetRouteValue("controller");
      var action = context.HttpContext.GetRouteValue("action");
      var info = $"控制器{controller}执行方法{action}的参数是{paramsdata}";
      //Console.WriteLine(info);
      //this.logger.LogInformation(info);
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
      var queryurl = context.HttpContext.Request.Path; // API请求地址
      var paramsdata = context.HttpContext.GetParams();
      var controller = context.HttpContext.GetRouteValue("controller");
      var headers = HttpContextExtendBase.Current.Request.Headers;
      if (headers.ContainsKey("X-Forwarded-For"))
      {
        HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
          headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
        );
      }
      var remoteIp =
        LogClass.GetIPAddress()
        + "|"
        + headers["X-Real-IP"].ToString()
        + "|"
        + headers["X-Forwarded-For"].ToString();
      if (string.Compare(remoteIp, "::1", true) == 0)
      {
        remoteIp = HttpContextExtendBase.Current.Connection.LocalIpAddress.MapToIPv4()?.ToString();
      }
      if (remoteIp.Split(':').Length >= 3)
      {
        remoteIp = remoteIp.Split(':')[3];
      }
      if (!string.IsNullOrEmpty(remoteIp))
      {
        remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
      }
      var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
      var ipaddress = string.Empty;
      var newripad = RemoteIpAddress.ToString();
      if (!string.IsNullOrEmpty(newripad))
      {
        if (string.Compare(newripad, "::1", true) != 0)
        {
          ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
        }
        else
        {
          ipaddress = remoteIp;
        }
      }
      else
      {
        ipaddress = remoteIp;
      }
      ipaddress = ipaddress.Replace("|::ffff:", "");
      var requestmode = context.HttpContext.Request.Method;
      var action = context.HttpContext.GetRouteValue("action");
      var queryheader = context.HttpContext.Request.Headers.ToList();
      var loginUserCode = HttpContextExtendBase.GetLoginCode();
      var result = string.Empty;
      if (
        string.Compare(queryurl.Value, "/api/User/DownFile", true) == 0
        || string.Compare(queryurl.Value, "/api/User/DownFileb", true) == 0
        || string.Compare(queryurl.Value, "/api/User/Downtaskfile", true) == 0
      )
      {
        var token = context.HttpContext.Request.Query.LastOrDefault().Value.ToString();
        loginUserCode = HttpContextExtendBase.GetLoginCode(token);
        result = paramsdata;
      }
      else
      {
        result = JsonConvert.SerializeObject(context.Result);
      }
      var requestmethod = context.HttpContext.Request.Method;

      Controllerexelog controllerexelog = new Controllerexelog()
      {
        name = controller.ToString(),
        method = action.ToString(),
        parameterdata = paramsdata,
        hearddata = JsonUtil.ToJson(queryheader),
        backresult = result,
        ucode = loginUserCode,
        ipaddress = ipaddress,
        requestmode = requestmode
      };
      if (
        string.Compare(queryurl.Value, "/api/Log/GetLogList", true) != 0
        && string.Compare(queryurl.Value, "/api/Log/GetLista", true) != 0
        && string.Compare(queryurl.Value, "/api/Log/GetListb", true) != 0
        && string.Compare(queryurl.Value, "/api/Log/GetListb", true) != 0
      )
      {
        if (string.Compare(controllerexelog.name, "Angular", true) != 0)
        {
          this.mySqlSugar.InserBackId(controllerexelog, out var msg);
        }
      }
    }
  }
}
